package vip.xiaonuo.digest;

import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import vip.xiaonuo.modular.devicemegvii.entity.DeviceMegvii;

import javax.validation.constraints.NotNull;
import java.util.Arrays;

public class DigestHttpClient {

    private static final long DEFAULT_SECONDS = 20;

    private static ConnectionKeepAliveStrategy connectionKeepAliveStrategy = (httpResponse, httpContext) -> {
        long timeOut = Arrays.asList(httpResponse.getHeaders(HTTP.CONN_KEEP_ALIVE))
                .stream()
                .filter(h -> StringUtils.equalsIgnoreCase(h.getName(), "timeout")
                        && StringUtils.isNumeric(h.getValue()))
                .findFirst()
                .map(h -> NumberUtils.toLong(h.getValue(), DEFAULT_SECONDS))
                .orElse(DEFAULT_SECONDS) * 1000;
        return timeOut;
    };

    public static HttpClient getDigestHttpClient(@NotNull String username, @NotNull String password, String host,Integer port){
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(
            new AuthScope(StringUtils.isBlank(host) ? AuthScope.ANY_HOST : host,
                port == null ? AuthScope.ANY_PORT : port),
            new UsernamePasswordCredentials(username,password));
        return HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).setKeepAliveStrategy(connectionKeepAliveStrategy).build();
    }

    public static HttpClient getDigestHttpClient(@NotNull DeviceMegvii device){
        String username = device.getWebAccount();
        String password = device.getWebPassword();
        return getDigestHttpClient(username,password,null,null);
    }

}
